package com.zuihai.app.mvp.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.zuihai.app.R;
import com.zuihai.app.di.component.DaggerMainComponent;
import com.zuihai.app.di.module.MainModule;
import com.zuihai.app.mvp.contract.MainContract;
import com.zuihai.app.mvp.model.entity.CheckUpdataResponse.CheckData;
import com.zuihai.app.mvp.model.entity.FindAddableColums;
import com.zuihai.app.mvp.model.entity.FindColums;
import com.zuihai.app.mvp.model.entity.HomeAddableColums;
import com.zuihai.app.mvp.model.entity.HomeColumss;
import com.zuihai.app.mvp.model.entity.mainhome.ColumnsDataSupport;
import com.zuihai.app.mvp.presenter.MainPresenter;
import com.zuihai.app.mvp.ui.activity.find.FindFragment;
import com.zuihai.app.mvp.ui.activity.home.HomeFragment;
import com.zuihai.app.mvp.ui.dialog.MessageDialog;
import com.zuihai.app.mvp.ui.dialog.ReleaseLoadingDialog;
import com.zuihai.app.mvp.ui.widget.MyToast;
import com.zuihai.app.mvp.ui.widget.bottomBar.BottomBarUrlTab;
import com.zuihai.app.mvp.ui.widget.bottomBar.BottomUrlBar;
import com.tbruyelle.rxpermissions.RxPermissions;

import org.litepal.crud.DataSupport;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;

public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View {
    @BindView(R.id.bottom_bar)
    BottomUrlBar mBottomBar;
    /*@BindView(R.id.iv_release)
    ImageView release;*/
    private BaseFragment[] mFragments;
    private MessageDialog mMessageDialog;
    private RxPermissions mRxPermissions;
    private long mExitTime;
    private int mCurrentPosition;
    private RxErrorHandler rxErrorHandler;
    private boolean isLoadPicture;
    private ReleaseLoadingDialog mLoadingDialog;

    public static void launchActivity(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    public static void launchActivity(Context context, boolean isLoad) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("is_load", isLoad);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMainComponent
                .builder()
                .appComponent(appComponent)
                .mainModule(new MainModule(this))
                .build()
                .inject(this);
        mRxPermissions = new RxPermissions(this);
        rxErrorHandler = mApplication.getAppComponent().rxErrorHandler();
      /*  PermissionUtil.luzhouAppPermission(new PermissionUtil.RequestPermission() {
            @Override
            public void onRequestPermissionSuccess() {
            }

            @Override
            public void onRequestPermisstionFailure() {
                ToastUtils.showShortToast("获取权限失败,可能导致部分功能无法使用!");
            }
        }, mRxPermissions, rxErrorHandler);*/
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mCurrentPosition = intent.getIntExtra("currentPosition", 1);
    }

    @Override
    protected View initView() {
        return LayoutInflater.from(this).inflate(R.layout.activity_main, null, false);
    }

    @Override
    protected void initData() {

        isLoadPicture = getIntent().getBooleanExtra("is_load", false);
        if (isLoadPicture) {
            LogUtils.e("一张新的图片 需要网络下载");
         /*   DataSupport kpLogo = DataSupport.findLast(KPLogoSupport.class);
            Glide.with(MainActivity.this).load(kpLogo);*/
        }
        // initDatabase();
        initContent();
        initBottom(); //初始化底部导航栏
        // checkUpdata();
    }

    private void initDatabase() {
        if (DataSupport.findAll(HomeColumss.class).size() == 0) {
            LogUtils.e("homecolums > 0");
            DataSupport.deleteAll(HomeColumss.class);
            DataSupport.deleteAll(HomeAddableColums.class);
            ArrayList<String> mList = new ArrayList();
            String[] mTitles = new String[]{"推荐", "头条", "图片", "热点", "故事"};
            String[] mTitles2 = new String[]{"视频"};
            //, "热点", "人物", "故事"
            //"推荐", "今日头条", "图片", "热点",
            for (int i = 0; i < mTitles.length; i++) {
                mList.add(String.valueOf(mTitles[i]));
            }

            List<HomeColumss> mainList = new ArrayList<HomeColumss>();
            for (int i = 0; i < mList.size(); i++) {
                HomeColumss homeColumss = new HomeColumss();
                homeColumss.setName(mList.get(i));
                mainList.add(homeColumss);
            }
            for (HomeColumss homeColumss : mainList) {
                homeColumss.save();
            }
            List<HomeAddableColums> moreList = new ArrayList<HomeAddableColums>();
            ArrayList<String> mAddableList = new ArrayList<>();
            mAddableList.add("视频");
            for (int i = 0; i < mAddableList.size(); i++) {
                HomeAddableColums homeAddableColums = new HomeAddableColums();
                homeAddableColums.setName(mAddableList.get(i));
                LogUtils.e("mAddableList.get(i) : " + mAddableList.get(i));
                moreList.add(homeAddableColums);
            }
            for (HomeAddableColums homeAddableColums : moreList) {
                homeAddableColums.save();
            }
        }

        if (DataSupport.findAll(FindColums.class).size() == 0) {
            LogUtils.e("findcolums > 0");
            DataSupport.deleteAll(FindColums.class);
            DataSupport.deleteAll(FindAddableColums.class);
            ArrayList<String> mFindAddedList = new ArrayList();
            String[] mFindTitles =
                    new String[]{"发现秘密"};
            //"推荐", "发现秘密", "有去处", "好货", "服务"
            //, "逛街", "周边"
            for (int i = 0; i < mFindTitles.length; i++) {
                mFindAddedList.add(String.valueOf(mFindTitles[i]));
            }

            List<FindColums> findaddedList = new ArrayList<FindColums>();
            for (int i = 0; i < mFindAddedList.size(); i++) {
                FindColums findColums = new FindColums();
                findColums.setName(mFindAddedList.get(i));
                findaddedList.add(findColums);
            }
            for (FindColums findColums : findaddedList) {
                findColums.save();
            }
            List<FindAddableColums> findAddableList = new ArrayList<FindAddableColums>();
            ArrayList<String> mfindAddableList = new ArrayList<>();
            // mfindAddableList.add("活动");
            // mfindAddableList.add("周边");
            // mfindAddableList.add("逛街");
            for (int i = 0; i < mfindAddableList.size(); i++) {
                FindAddableColums findAddableColums = new FindAddableColums();
                findAddableColums.setName(mfindAddableList.get(i));
                findAddableList.add(findAddableColums);
            }
            for (FindAddableColums findAddableColums : findAddableList) {
                findAddableColums.save();
            }
        }
    }

    private void checkUpdata() {
        //mPresenter.checkUpdata();
    }

    @Subscriber(tag = "setFriends")
    public void update(String msg) {
        showHideFragment(mFragments[3]);
        mBottomBar.setCurrentItem(3);
    }

    /**
     * 初始化底部导航栏
     */
    private void initBottom() {
        List<ColumnsDataSupport> allHomeColus = DataSupport.findAll(ColumnsDataSupport.class);
        for (int i = 0; i < 2; i++) {
            String iconSelected = allHomeColus.get(i).getSelectedIcon();
            String iconSelect = allHomeColus.get(i).getIcon();
            String title = allHomeColus.get(i).getName() + "";
            LogUtils.e(iconSelect + "-" + iconSelect);
            mBottomBar.addItem(new BottomBarUrlTab(this, iconSelected, iconSelect, title, i));
        }
        mBottomBar.setOnTabSelectedListener(new BottomUrlBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position, int prePosition) {
                mCurrentPosition = position;
                if (position == 2) {

                    mBottomBar.setCurrentItem(prePosition);
                } else {
                    showHideFragment(mFragments[position]);
                }
                if (position == 4) {
                    BarUtils.setColorNoTranslucent(MainActivity.this, getResources().getColor(R.color.myToolbarBackground));
                } else {
                    BarUtils.setColorNoTranslucent(MainActivity.this, getResources().getColor(R.color.colorPrimaryDark));
                }
            }

            @Override
            public void onTabUnselected(int position) {
            }

            @Override
            public void onTabReselected(int position) {
            }
        });
        mBottomBar.setCurrentItem(mCurrentPosition);
    }

    /**
     * 初始化Fragment
     */
    private void initContent() {

        mFragments = new BaseFragment[]{
                HomeFragment.newInstance(),
                FindFragment.newInstance(),
                //FindFragment.newInstance(),
              //  FriendHomeFragment.newInstance(),
                //  MyColumnFragment.newInstance()
        };
        loadMultipleRootFragment(R.id.content_layout, 0, mFragments);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        savedInstanceState.putInt("currentPosition", mCurrentPosition);
    }

    @Override
    public void showLoading() {
        LogUtils.e("事件总线 showLoading");
        mLoadingDialog=new ReleaseLoadingDialog(MainActivity.this);
        mLoadingDialog.show();
    }

    @Override
    public void hideLoading() {
        LogUtils.e("事件总线 hideLoading");
        mLoadingDialog.dismiss();
        mLoadingDialog=null;
    }

    @Subscriber(tag = "_main_showDialog")
    public void mainShowDialog(String getText) {
        LogUtils.e("_main_showDialog");
        //showLoading();
    }

    @Subscriber(tag = "_main_hideDialog")
    public void mainHideDialog(String getText) {
        LogUtils.e("_main_hideDialog");
        //hideLoading();
    }

    @Override
    public void showMessage(String message) {
        MyToast.showSuccess(message);
    }

    @Override
    public void showUpdata(CheckData checkData) {
        String url = checkData.downloadUrl;
       /* new MessageDialog
                .Build(this)
                .setMessage(checkData.description)
                .setTitle(String.format("新版本%s", checkData.version))
                .setConfrimClickListener(new MessageDialog.OnConfrimClickListener() {
                    @Override
                    public void confrimClick(MessageDialog dialog) {
                        PermissionUtil.externalStorage(new PermissionUtil.RequestPermission() {
                            @Override
                            public void onRequestPermissionSuccess() {
                                String saveName = url.substring(url.lastIndexOf("/") + 1);
                                DownloadService.startService(MainActivity.this, saveName, url);
                                dialog.dismiss();
                            }
                            @Override
                            public void onRequestPermisstionFailure() {
                                ToastUtils.showShortToast("获取权限失败，不能进行更新");
                            }
                        }, mRxPermissions);
                    }
                })
                .show();*/
    }


    @Override
    public void onBackPressedSupport() {
        if (System.currentTimeMillis() - mExitTime > 2000) {
            MyToast.showSuccess("再按一次退出!");
        } else {
            super.onBackPressedSupport();
        }
        mExitTime = System.currentTimeMillis();
    }

}
